import { observable, action, toJS } from 'mobx';
import { message } from 'antd';
import isFunction from 'lodash/isFunction';
import Apis from '../apis/cowork';
import * as disManageApis from '../apis/discussManage';
import _remove from 'lodash/remove';
import { WeaTableNew, WeaLogView, WeaForm } from 'comsMobx';

const { TableStore } = WeaTableNew;
import { WeaLocaleProvider } from 'ecCom';
import { richfilter } from '../util/CoworkUtil';
import ParticipationStore from './cowork/Participation';

const { LogStore } = WeaLogView;
const getLabel = WeaLocaleProvider.getLabel;

const initResource = {
  docList: [],
  cusList: [],
  taskList: [],
  mutilprjList: [],
  accList: [],
  wfList: [],
  status: '',
  readed: false,
};
const initStat = {
  alist: [],
  noReadids: [],
  parter: [],
  typemanagerids: [],
  status: '',
  readed: false,
};
const initParams = {
  type: 'all',
  labelid: 'allTab',
  orderType: 'important',
  layout: 0,
  mainid: '',
  pagesize: '30',
  pageNum: 1,
};
class CoworkStore {
  @observable logStore = new LogStore();
  @observable participationStore = new ParticipationStore();
  @observable leftList = {
    datas: [],
    sessionkey: '',
    loading: false,
    ended: false,
    checkIds: [],
    checkAll: false,
    alertPage: false,
    params: { ...initParams },
    form: new WeaForm(), // 列表模式高级搜索
    condition: [], // 列表模式高级搜索内容
    showSearchAd: false,
  };
  @observable content = {
    id: '',
    cowork: null,
    searchParams: {},
    searchForm: new WeaForm(),
    page: {
      current: 1,
      total: 0,
      pageSize: 20,
    },
    accessoryPath: {},
    recordList: [],
    replyListViewRight: 1,
    checkIds: [],
    checkAll: false,
    batchOperate: false,
    pendApprove: false,
    sessionkey: '',
    logViewCondition: [],
    loading: true,
    recordLoading: true,
    relateLoading: true,

    // 与我相关参数
    relateParams: {},
    relateMeList: [],
  };

  @observable logList = {
    sessionkey: '',
    viewRight: 0,
    logLoading: true,
  };

  @observable contentId = '';
  @observable logstatus = {
    targetId: '',
    logType: '24', // 日志相关参数
    logSmallType: '4',
  };

  // 协作详情
  @observable detailParams = {
    showSearchAd: false,
    tabKey: 'list',
    edit: false,
  };

  // 3 数据在store中的数据结构
  // 相关资源
  @observable resource = { ...initResource };

  // 参与情况
  @observable stat = { ...initStat };

  // 协作-协作交流-获取当事人能查看的协作区类型集合
  @observable typeList = {
    myDefCoworkTypeList: [],
    myCoworkTypeList: [],
    status: '',
  };
  // 协作-获取协作类别下拉框
  @observable comboList = {
    CoMainTypeList: [],
    status: '',
  };

  // 协作-获取协作版块对象
  @observable typeVo = {
    coworkTypeMap: [],
    status: '',
  };

  // 协作-用户主界面操作权限
  @observable authority = {
    status: '',
    clientMap: {},
    coworkTypeAuthority: '',
    coworkMaintypeAuthority: '',
  };

  /** 左侧树store */
  @observable selectedTreeKeys = [];
  @observable treeList = {
    treeCounts: [],
    treeDatas: [],
    treeTypes: [],
  };

  @observable mainTypeForm = new WeaForm();

  // 配置项
  @observable config = {
    appStatus: {},
    discussSearch: {},
    labelList: [], // 标签列表
    tagVisible: false,
    typeListSessionKey: '', // 版块列表
    mainTypeListSessionKey: '', // 版块列表
    authority: {},
    authConditions: [],
    editId: '',
  };

  @observable comsWeaTableStore = new TableStore();
  @observable logTableStore = new TableStore(); // 日志表格
  @observable mainTypeTableStore = new TableStore(); // 类别表格
  @observable typeTableStore = new TableStore(); // 版块表格
  @observable logTableForm = new WeaForm();

  //         --  新建、编辑协作相关 --
  @observable createForm = new WeaForm();
  @observable createTable = new TableStore();
  @observable newCoworkStatus = {
    showNewCowork: false,
    createOrEdit: 0,
    selectedKey: 0,
    createCondition: [],
    createList: [],
    authCondition: [],
    showAuth: false,
    saveLoading: false,
    selectValue: '',
    associateList: [], // 版块绑定的一些详细字段通过key关联 -- 控制允许匿名 0：不显示 1：显示
    itemsVO: undefined,
  };

  @observable loaded = false;
  @observable initing = true;

  @observable doCoworkFieldInit = false;
  @observable isEllipse = false;

  @observable tagLoading = false; // 标签设置页面Loading
  @observable formJoinType = '0'; // 记录高级搜索joinType值

  @action
  doInit = (callback) => {
    this.leftList = {
      ...this.leftList,
      // form: new WeaForm(),//高级搜索条件
      showSearchAd: false,
    };
    this.clearParams();
    this.init(callback);
  };

  @action setLeftListParams = (params) => {
    Object.keys(params).forEach((key) => {
      this.leftList[key] = params[key];
    });
  };

  @action setStoreState = (params = {}) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
  };

  // 进入页面初始化调用
  init = (callback) => {
    this.initing = true;
    this.getCoworkViewType(callback);
  };

  @action getCoworkViewType = (callback) => {
    Apis.getCoworkViewType().then((res) => {
      this.leftList.params.layout = res.layout || 1; // 1--2栏视图，2--列表视图
      this.formJoinType = res.joinType || '0';
      Promise.all([
        // this.getCoworkAppStatus(),//富文本下方按钮
        this.getDiscussRecordCondition(), // 高级搜索条件
        this.getCoworkLabelList(), // 标签设置
        // 获取左侧高级搜索查询条件
        this.getCoworkCondition(callback),
        this.getAuthorityByUser(),

        this.getMyCoworkTypeList(),
        this.coworkAuthorityByUser(),

        // 获得查看日志搜索条件
        this.getLogViewCondition(),
      ]).then(() => {
        this.initing = false;
      });
    });
  };

  @action coworkChangeView = params => Apis.coworkChangeView(params);

  setLoaded = bool => (this.loaded = bool);

  setSearchAd = bool => (this.leftList.showSearchAd = bool); // 高级搜索显示隐藏

  // 协作详情参数初始化 fix:切换同一个协作主题也可以再次刷新
  initDetailParams = () => {
    this.detailParams = {
      ...this.detailParams,
      showSearchAd: false,
      tabKey: 'list',
      edit: false,
    };
  };

  setDetailParams = (params, callback) => {
    let detailParams = { ...this.detailParams };
    Object.keys(params).forEach((key) => {
      detailParams[key] = params[key];
    });
    this.detailParams = detailParams;
    if (callback) callback();
  };

  doFormReset = () => {
    this.leftList.form.resetForm();
    this.leftList.form.initFormFields(toJS(this.leftList.condition));
  };

  // 获取协作左侧列表
  getLeftList = (otherParams) => {
    if (this.leftList.params.layout == 1 && this.leftList.ended) {
      return;
    }
    this.leftList.loading = true;
    let { params } = this.leftList;
    const listParams = this.leftList.form.getFormParams();
    Apis.getCoworkList({ ...params, ...listParams }).then((result) => {
      this.leftList.loading = false;
      if (!result) {
        return;
      }
      if (result.coworkList) {
        let datas = this.leftList.datas.map(data => data);
        if (otherParams && otherParams.reload) {
          datas = [];
        }
        if (Array.isArray(result.coworkList) && result.coworkList.length > 0) {
          datas = datas.concat(result.coworkList);
          this.leftList.checkAll = false;
        } else {
          this.leftList.ended = true;
        }
        this.leftList.datas = datas;
        // 处理是否显示暂无数据
        if (datas.length == 0) {
          this.leftList.alertPage = true;
        } else {
          this.leftList.alertPage = false;
        }
      }
      if (result.sessionkey) {
        this.leftList.sessionkey = result.sessionkey;
        this.comsWeaTableStore.getDatas(result.sessionkey, 1);
      }
    });
  };

  reloadLeftList = () => {
    this.leftList = {
      ...this.leftList,
      datas: [],
      params: { ...this.leftList.params, pageNum: 1 },
      ended: false,
      checkIds: [],
    };
    this.getLeftList({ reload: true });
  };

  // 修改API参数
  setParams = (params) => {
    this.leftList.params = { ...this.leftList.params, ...params };
  };

  clearParams = () => {
    this.setParams(initParams);
    this.leftList.form.reset();
  };

  // 标记协作类型
  @action
  markItemAsType = (params) => {
    let { type } = params,
      saveParams = { ...params };
    if (type == 'tag') {
      this.getCoworkLabelList();
      this.setTagVisible(true);
      return;
    }
    if (!isNaN(parseInt(type))) {
      saveParams.type = 'addLabel';
      saveParams.labelIds = type;
    }
    this.leftList.loading = true;
    Apis.markItemAsType(saveParams).then((result) => {
      if (result.status == 1 && result.api_status) {
        let ids = params.coworkids || '',
          idArray = ids.split(',');
        if (type == 'hidden' || type == 'show') {
          this.reloadLeftList();
          return;
        }
        if (
          isNaN(parseInt(type)) &&
          type != 'deleteAll' &&
          this.leftList.params.layout == 1
        ) {
          let newProps = {};
          switch (type) {
            case 'read':
              newProps.isnew = '0';
              break;
            case 'unread':
              newProps.isnew = '1';
              break;
            case 'important':
              newProps.important = '1';
              break;
            case 'normal':
              newProps.important = '0';
              break;
          }
          this.leftList.datas = this.leftList.datas.map((data) => {
            if (idArray.some(id => id == data.coworkid)) {
              return { ...data, ...newProps };
            }
            return data;
          });

          if (idArray.some(id => id == this.content.id)) {
            switch (type) {
              case 'important':
                this.content.cowork.isCoworkImportant = '1';
                break;
              case 'normal':
                this.content.cowork.isCoworkImportant = '0';
                break;
            }
          }
        } else {
          this.reloadLeftList();
          this.chooseCowork(this.content.id, this.content.floorNum);
        }
        this.leftList.loading = false;
      } else {
        message.error(result.message || getLabel(4715, '操作失败'));
        this.leftList.loading = false;
      }
    });
  };

  // 获取高级查询搜索条件
  getCoworkCondition = (callback) => {
    Apis.getCoworkItemRecordCondition().then((result) => {
      if (!result) return;
      this.leftList = {
        ...this.leftList,
        condition: result.conditioninfo,
      };
      this.leftList.form = new WeaForm();
      this.leftList.form.initFormFields(result.conditioninfo, () => {
        if (callback) callback(); // 门户传入name用
        this.leftList.form.updateFields({
          jointype: { value: this.formJoinType },
        });
        this.reloadLeftList();
      });
      this.config.authConditions = result.authConditions;
    });
  };

  @action changeJoinType = async (params) => {
    let result = await Apis.coworkChangeJoinType(params);
    if (!result.flag) {
      message.warning(getLabel('521589', '存储参与类型失败，请重试！'));
    }
  };

  // 获取form当前的值
  @action getFormParams = () => this.logTableForm.getFormParams();

  @action clearFormFields = () => {
    this.logTableForm.resetConditionValue();
  };

  // 查看日志数据获取
  @action getLog = (params) => {
    let resultParams = this.getFormParams();
    resultParams = { ...resultParams, ...params };
    this.logList.logLoading = true;
    Apis.getLog(resultParams).then(
      action('fetchSuccess', (result) => {
        if (!result) return;
        this.logList.sessionkey = result.sessionkey;
        this.logList.viewRight = result.viewRight;
        this.logTableStore.getDatas(result.sessionkey, 1);
        this.logList.logLoading = false;
      }),
    );
  };

  @action reSetLogStore = () => (this.logTableStore = new TableStore());

  chooseCowork = (id, floorNum = '', callback) => {
    this.content.id = id;
    this.contentId = id;
    this.content.searchForm.isFormInit &&
      this.content.searchForm.updateFields({
        srchFloorNum: { value: floorNum || '' },
      });
    this.content.searchParams = { srchFloorNum: floorNum };
    if (id) {
      this.content.loading = true;
      this.content.recordList = [];
      this.content.relateMeList = [];
      Apis.viewCowork({ coworkId: id }).then((result) => {
        this.content.batchOperate = false;
        this.content.pendApprove = false;
        this.content.cowork = result;
        this.reloadRecordList({}, () => {
          this.content.loading = false;
        });
        this.getCoworkAccessory(result.itemsVO && result.itemsVO.typeid);
        this.stat = { ...initStat };
        this.resource = { ...initResource };
        this.content.relateLoading = true;
        this.leftList.datas = this.leftList.datas.map((data) => {
          if (data.coworkid == id) {
            return { ...data, isnew: '0' };
          }
          return data;
        });
        isFunction(callback) && callback(result);
      });
    }
  };

  reloadCowork = (isquit = false, callback) => {
    let id = this.content.id;
    if (id) {
      Apis.viewCowork({ coworkId: id }).then((result) => {
        this.content.cowork = result;
        if (isquit) this.content.cowork = { ...result, isquit: true };
        if (callback && typeof callback === 'function') callback();
      });
    }
  };

  setContentParams = (params = {}) => {
    Object.keys(params).forEach((key) => {
      this.content[key] = params[key];
    });
  };

  queryRecordList = (outerParams, callback) => {
    let { id, page, searchParams } = this.content;
    if (!id) {
      this.content.recordList = [];
      return;
    }
    let params = {
      ...searchParams,
      coworkId: id,
      recordType: 'common',
      currentPage: page.current,
      ...outerParams,
    };
    params.isShowApproval = this.content.pendApprove ? 1 : '';
    this.content.recordLoading = true;
    Apis.discussRecord(params).then((result) => {
      this.content.recordList = result.recordList;
      params.srchcontent &&
        this.content.recordList.map((item) => {
          // 内容搜索高亮显示
          item.remark = richfilter(item.remark, params.srchcontent);
        });
      this.content.page = {
        current: result.currentPage,
        total: result.total,
        pageSize: result.pageSize,
      };
      this.content.replyListViewRight = result.viewRight;
      this.content.checkIds = [];
      this.content.checkAll = false;
      this.content.recordLoading = false;
      isFunction(callback) && callback();
    });
  };

  reloadRecordList(outerParams, callback) {
    let params = { ...outerParams, currentPage: 1 };
    this.queryRecordList(params, callback);
  }

  queryRelateMeList = (type) => {
    let params = {};
    let { id } = this.content;
    if (!type && id) {
      params.coworkId = id;
      params.recordType = 'relatedme';
    } else {
      params.dateType = type || 'week';
      params.recordType = 'related';
    }
    this.content.relateParams = params;
    this.queryRelateMePage();
  };

  queryRelateMePage = (current) => {
    let { relateParams, page } = this.content;
    let params = { ...relateParams, currentPage: page.current };
    if (current || current === 0) {
      params.currentPage = current;
    }
    this.content.relateLoading = true;
    Apis.discussRecord(params).then((result) => {
      this.content.relateMeList = result.recordList;
      this.content.page = {
        current: result.currentPage,
        total: result.total,
        pageSize: result.pageSize,
      };
      this.content.relateLoading = false;
      this.content.replyListViewRight = result.viewRight;
    });
  };

  // 2 定义方法，从后台取数据
  // 相关资源
  getCoworkDiscussData = () => {
    let id = this.content.id;
    this.resource.readed = false;
    Apis.getResource({ coworkId: id }).then((result) => {
      this.resource = { ...result, readed: true };
    });
  };
  // 参与情况
  getShareConditionStrList = () => {
    let id = this.content.id;
    Apis.getShareStat({ coworkId: id, type: 'all' }).then((result) => {
      this.stat = { ...result, readed: true };
    });
  };

  // 协作-协作交流-获取当事人能查看的协作区类型集合
  getMyCoworkTypeList = () => {
    Apis.getMyCoworkTypeList().then((result) => {
      this.typeList = result;
    });
  };

  // 协作-获取协作类别对象
  getCoworkMainTypeComboList = () => {
    Apis.getComboList().then((result) => {
      this.comboList = result;
    });
  };

  // 协作-新建/编辑 协作版块对象
  saveOrUpdateCoworkTypeVo = (params, func) => {
    Apis.saveOrUpdateTypeVo(params).then((result) => {
      if (params && result && result.flag) {
        func(result);
        this.getCoworkTreeDatas();
      } else {
        if (result && result.message) {
          message.error(result.message);
          return;
        }
        message.error('保存协作版块失败');
      }
    });
  };

  // 协作-用户主界面操作权限
  coworkAuthorityByUser = () => {
    Apis.getAuthorityByUser().then((result) => {
      this.authority = result;
    });
  };

  getCoworkAppStatus = () => {
    Apis.getCoworkAppStatus().then((result) => {
      this.config.appStatus = result.appStatus;
    });
  };

  submitCoworkDiscuss = (params, tabKey, callback) => {
    if (!this.content.id) {
      message.info(getLabel(382670, '请选择一个协作'));
      return false;
    }
    params.coworkId = this.content.id;
    Apis.submitCoworkDiscuss(params).then((result) => {
      if (result.status == 1) {
        let { replyType, topdiscussid } = params;
        let list =
          tabKey == 'list'
            ? toJS(this.content.recordList)
            : toJS(this.content.relateMeList);
        // 评论时，只更新该组评论列表
        if (replyType == 'comment') {
          let func = (record) => {
            if (record.id == topdiscussid) {
              return { ...record, commonList: result.commonList };
            }
            return record;
          };
          if (tabKey == 'list') {
            this.content.recordList = list.map(func);
          } else {
            this.content.relateMeList = list.map(func);
          }
        } else if (params.id) {
          // 编辑时，只更新该内容
          let func = (record) => {
            if (record.id == params.id) {
              if (result.flag === false) {
                message.error(result.message);
              } else {
                return result.recordList[0];
              }
            }
            return record;
          };
          if (tabKey == 'list') {
            this.content.recordList = list.map(func);
          } else {
            this.content.relateMeList = list.map(func);
          }
        } else {
          // 发表、引用时，直接刷新列表
          this.reloadRecordList();
        }
        isFunction(callback) && callback();
      }
    });
  };

  operateDicsuss = (params, type) => {
    Apis.operateDicsuss(params).then((result) => {
      if (result.status == 1) {
        let { operationType, id } = params;
        let func = null;
        switch (operationType) {
          case 'collect':
            func = (record) => {
              if (record.id == id) {
                return {
                  ...record,
                  isMeCollected: record.isMeCollected == 1 ? 0 : 1,
                };
              }
              return record;
            };
            break;
          case 'delDiscuss':
            if (result.recordList) {
              func = (record) => {
                if (record.id == id) {
                  return result.recordList && result.recordList[0];
                }
                return record;
              };
            } else if (!result.flag) {
              this.reloadRecordList();
              message.error(
                getLabel('520107', '信息已超过可删除时间，或者您无操作权限'),
              );
            } else if (type == 'my') {
              this.content.relateMeList = this.content.relateMeList.filter(
                record => record.id != id,
              );
            } else {
              this.content.recordList = this.content.recordList.filter(
                record => record.id != id,
              );
            }
            break;
          case 'agree':
            func = (record) => {
              if (record.id == id) {
                let num = parseInt(record.zanCount);
                num = isNaN(num) ? 0 : num;
                if (record.isMeZaned == 1) {
                  return { ...record, isMeZaned: 0, zanCount: num - 1 };
                }
                return { ...record, isMeZaned: 1, zanCount: num + 1 };
              }
              return record;
            };
            break;
          case 'delComment':
            func = (record) => {
              if (record.id == params.discussId && result.flag) {
                return { ...record, commonList: result.commonList };
              } else if (!result.flag) {
                message.error(getLabel('517403', '您无权限对当前评论做出操作'));
                this.reloadRecordList();
              }
              return record;
            };
            break;
          default:
            if (type == 'my') {
              this.queryRelateMeList();
            } else {
              this.queryRecordList();
            }
        }
        if (func != null) {
          if (type == 'my') {
            this.content.relateMeList = this.content.relateMeList.map(func);
          } else {
            this.content.recordList = this.content.recordList.map(func);
          }
        }
      }
    });
  };

  check = (id, bool) => {
    if (bool == 1) {
      this.content.checkIds.push(id);
      this.content.checkAll =
        this.content.checkIds.length == this.content.recordList.length;
    } else {
      _remove(this.content.checkIds, checkId => checkId == id);
      this.content.checkAll = false;
    }
  };

  checkAll = (bool) => {
    if (bool == 1) {
      this.content.checkIds = this.content.recordList.map(
        record => record.id,
      );
    } else {
      this.content.checkIds = [];
    }
    this.content.checkAll = bool;
  };

  batchDelete = (value) => {
    let ids = this.content.checkIds;
    disManageApis
      .batchDiscussDel({ discussIds: ids.join(), isDeleteAll: parseInt(value) })
      .then((result) => {
        if (result.status) {
          this.queryRecordList();
        }
      });
  };

  setBatchOperate = () => {
    this.content.batchOperate = !this.content.batchOperate;
  };

  setPendApprove = () => {
    this.content.pendApprove = !this.content.pendApprove;
    this.reloadRecordList();
  };

  batchApprove = () => {
    let ids = this.content.checkIds;
    Apis.batchDiscussApprove({ discussIds: ids.join() }).then((result) => {
      if (result.status) {
        this.queryRecordList();
      }
    });
  };

  // 获取查看日志高级搜索条件
  @action getLogViewCondition = () => {
    Apis.getLogViewCondition().then((result) => {
      if (!result) return;
      this.content.logViewCondition = result.conditioninfo;
      this.logTableForm.initFormFields(result.conditioninfo);
    });
  };

  @action clearLogViewCondition = () => {
    this.content.logViewCondition = [];
  };

  getDiscussRecordCondition = () => {
    Apis.getDiscussRecordCondition().then((result) => {
      this.config.discussSearch = result;
      this.content.searchForm = new WeaForm();
      this.content.searchForm.initFormFields(result.conditioninfo, () => {
        let { srchFloorNum } = this.content.searchForm.getFormParams();
        if (srchFloorNum != this.content.searchParams.srchFloorNum) {
          this.content.searchForm.updateFields({
            srchFloorNum: { value: this.content.searchParams.srchFloorNum },
          });
        }
      });
    });
  };

  onTreeSelect = (typeId, mainTypeId) => {
    this.setParams({ mainid: mainTypeId });
    this.leftList.form.updateFields({
      typeid: { value: typeId },
    });
    this.reloadLeftList();
  };

  searchDiscussList = (params) => {
    this.content.searchParams = params;
    this.reloadRecordList();
  };

  @action getCoworkLabelList = (callback) => {
    this.tagLoading = true;
    Apis.getCoworkLabelList().then(
      action('fetchSuccess', (result) => {
        if (!result) {
          message.error(getLabel(192, '获取标签设置列表失败！', 'error'));
        } else {
          this.config.labelList = result.labelList;
          isFunction(callback) && callback();
        }
        this.tagLoading = false;
      }),
    );
  };

  setTagVisible = (bool) => {
    this.config.tagVisible = bool;
  };

  checkLeftList = (id, e) => {
    if (e.target.checked) {
      this.leftList.checkIds.push(id);
      this.leftList.checkAll =
        this.leftList.checkIds.length == this.leftList.datas.length;
    } else {
      _remove(this.leftList.checkIds, checkId => checkId == id);
      this.leftList.checkAll = false;
    }
  };

  checkLeftListAll = (e) => {
    if (e.target.checked) {
      this.leftList.checkIds = this.leftList.datas.map(item => item.coworkid);
    } else {
      this.leftList.checkIds = [];
    }
    this.leftList.checkAll = e.target.checked;
  };

  // 获得协作版块列表
  getCoworkTypeList = () => {
    Apis.getCoworkTypeList().then((result) => {
      if (result.status == 1) {
        this.config.typeListSessionKey = result.sessionkey;
        this.typeTableStore.getDatas(result.sessionkey, 1);
      } else {
        message.error(getLabel(194, '读取协作版块失败', 'error'));
      }
    });
  };

  // 批量删除版块
  batchDeleteCoworkType = (ids) => {
    let idStr = ids;
    if (Array.isArray(ids)) {
      idStr = ids.join();
    }
    Apis.batchDeleteCoworkType({ ids: idStr }).then((result) => {
      if (result.status == 1) {
        this.getCoworkTypeList();
      } else {
        message.error(getLabel(195, '删除协作版块失败', 'error'));
      }
    });
  };

  // 获得协作类别列表
  getCoworkMainTypeList = () => {
    Apis.getCoworkMainTypeList().then((result) => {
      if (result.status == 1) {
        this.config.mainTypeListSessionKey = result.sessionkey;
        this.mainTypeTableStore.getDatas(result.sessionkey);
      } else {
        message.error(getLabel(196, '读取协作类别失败', 'error'));
      }
    });
  };

  batchDeleteCoworkMainType = (ids) => {
    let idStr = ids;
    if (Array.isArray(ids)) {
      idStr = ids.join();
    }
    Apis.batchDeleteCoworkMainType({ ids: idStr }).then((result) => {
      if (result.status == 1) {
        this.getCoworkMainTypeList();
      } else {
        message.error(getLabel(197, '删除协作类别失败', 'error'));
      }
    });
  };

  saveCoworkMainTypeVo = (params, callback) => {
    Apis.saveCoworkMainTypeVo(params).then((result) => {
      if (result.status == 1 && result.flag) {
        this.getCoworkMainTypeList();
        this.getCoworkMainTypeComboList();
        this.getCoworkTreeDatas();
        callback();
      } else if (result.message) {
        message.error(result.message);
      } else {
        message.error(getLabel(198, '保存协作类别失败', 'error'));
      }
    });
  };

  uploadCoworkLabelList = (params, callback) => {
    Apis.uploadCoworkLabelList(params).then((result) => {
      if (result.status == 1 && result.flag) {
        callback();
        this.getCoworkLabelList();
      } else {
        message.error(getLabel(199, '保存协作标签失败', 'error'));
      }
    });
  };

  // 获得用户权限
  getAuthorityByUser = () => {
    Apis.getAuthorityByUser().then((result) => {
      if (result.status == 1) {
        this.config.authority = {
          mainType: result.coworkMaintypeAuthority,
          type: result.coworkTypeAuthority,
          userid: result.clientMap.id,
        };
      } else {
        message.error(getLabel(200, '获得用户权限失败', 'error'));
      }
    });
  };

  // 删除协作标签
  deleteCoworkLabels = (label, id) => {
    Apis.deleteCoworkLabels({ labelItemId: label.labelitemid }).then(
      (result) => {
        if (result.status == 1 && result.api_status) {
          if (this.content.id == id) {
            let labelBycoworkList = toJS(this.content.cowork.labelBycoworkList);
            this.content.cowork.labelBycoworkList = labelBycoworkList
              ? labelBycoworkList.filter(item => label.id != item.id)
              : [];
          }
          this.leftList.datas = this.leftList.datas.map((data) => {
            if (data.coworkid == id) {
              let { labelBycoworkList = [] } = data;
              return {
                ...data,
                labelBycoworkList: labelBycoworkList.filter(
                  item => label.id != item.id,
                ),
              };
            }
            return data;
          });
        } else {
          message.error(getLabel(201, '删除协作标签失败', 'error'));
        }
      },
    );
  };

  getCoworkTreeDatas = () => {
    Apis.getCoworkTreeDatas().then((result) => {
      this.treeList = {
        treeCounts: result.treeCounts,
        treeDatas: result.treeDatas,
        treeTypes: result.treeTypes,
      };
    });
  };

  @action setSelectedTreeKeys = (key = []) => {
    this.selectedTreeKeys = key;
  };

  operateCoworkItem = (coworkId, operationType) => {
    Apis.coworkItemOperation({ coworkId, operationType }).then((result) => {
      if (result.status == 1 && result.flag) {
        if (coworkId == this.content.id) {
          this.chooseCowork(coworkId);
          this.queryRecordList();
          this.queryRelateMeList();
        }
        this.reloadLeftList();
      } else {
        message.error(getLabel(203, '处理协作失败', 'error'));
      }
    });
  };

  markTable = (idArray, type) => {
    let newProps = {};
    switch (type) {
      case 'read':
        newProps.isnew = '0';
        break;
      case 'unread':
        newProps.isnew = '1';
        break;
      case 'important':
        newProps.important = '1';
        break;
      case 'normal':
        newProps.important = '0';
        break;
    }
    let datas = this.comsWeaTableStore.datas.map((data) => {
      if (idArray.some(id => id == data.id)) {
        return { ...data, ...newProps };
      }
      return data;
    });
    this.comsWeaTableStore.tableUpdate({
      datas,
    });
  };

  getCoworkAccessory = (typeId) => {
    Apis.getCoworkAccessory({ typeId }).then((result) => {
      if (result.status == '1') {
        this.content.accessoryPath = result;
      } else {
        message.error(
          getLabel(204, '读取协作附件失败, msg:', 'error') + result.msg,
        );
      }
    });
  };

  setCoworkRead = () => {
    this.content.cowork && (this.content.cowork.isRead = '0');
  };

  //                                             ---     新建编辑协作相关    ----
  setCreateState = (params = {}) => {
    let newCoworkStatus = { ...this.newCoworkStatus };
    Object.keys(params).forEach((key) => {
      newCoworkStatus[key] = params[key];
    });
    this.newCoworkStatus = newCoworkStatus;
  };

  doCreateFormInit = (condition) => {
    this.createForm = new WeaForm();
    this.createForm.initFormFields(
      condition || toJS(this.newCoworkStatus.createCondition),
    );
    window.e9ChangedFormFieldKey = 'sjldkvokddkaq';
  };

  /* 退出协作 */
  quitCowork = () => {
    let params = { coworkId: this.content.id };
    Apis.quitCowork(params).then((res) => {
      if (res.flag) {
        message.success(getLabel('513434', '退出协作成功！'));
        this.reloadLeftList();
        this.reloadCowork(true);
      } else {
        let msg = '操作失败';
        if (res.canQuit !== '1' && res.message) msg = res.message;
        message.error(msg);
      }
    });
  };

  // 应内容导出
  coworkLogExport = (params) => {
    let resultParams = this.getFormParams();
    resultParams = { ...resultParams, ...params };
    Apis.coworkLogExport(resultParams).then(() => {
      window.location = '/weaver/weaver.file.ExcelOut';
    });
  };
}

const coworkMainStore = new CoworkStore();
export default coworkMainStore;
